package com.kaguya.vams.security.handler;

import cn.hutool.json.JSONUtil;
import com.kaguya.vams.domain.Result;
import com.kaguya.vams.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 登录成功处理器
 * @author : kaguya
 * @date : 14:02 2021/7/30
 */
@Slf4j
@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {

    @Autowired
    JwtUtils jwtUtils; //jwt生成工具类

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {

        log.info("登录成功处理器 - 生成jwt，并放置到请求头中");

        httpServletResponse.setContentType("application/json;charset=UTF-8");
        ServletOutputStream sos = httpServletResponse.getOutputStream();

        //生成jwt，并放置到请求头中
        /*
        authentication.getName() 获取用户名
        generateToken生成jwt，用户名放在载荷里
         */
        String jwt = jwtUtils.generateToken(authentication.getName());
        //设置请求头
        httpServletResponse.setHeader(jwtUtils.getHeader(),jwt);

        Result result = Result.ok();
        //转成json并写入
        sos.write(JSONUtil.toJsonStr(result).getBytes("UTF-8"));

        sos.flush();
        sos.close();
    }
}
